<?php
/**
 * Created by PhpStorm.
 * User: Lzhy ysjywz@gmail.com
 * Date: 2019/8/18
 * Time: 11:28 AM
 */
namespace app\admin\controller;

use app\admin\event\Dt;
use think\Db;
use think\facade\Request;

class Wuser extends Base
{
    public function index()
    {
        $wechatList = Db::table('wechat')->field('id,name,wechat_id')->cache(30)->select();
        $wechatListById = array_column($wechatList,'name','wechat_id');
        
        if(Request::isPost()){
            $params = Request::param();
            $where = [];
            if(isset($params['wechat_id']) && $params['wechat_id']){
                $where[] = ['wechat_id','=',$params['wechat_id']];
            }
            if(isset($params['keyword']) && $params['keyword']){
                $where[] = ['nickname|openid','like',$params['keyword'].'%'];
            }

            $dt = new Dt();
            $data = $dt->table('wuser')
                ->format([
                    'sex' => ['未知','男','女'],
                    'subscribe' => ['未关注','关注'],
                    'wechat_id' => $wechatListById
                ])
                ->fetch($where);
            foreach ($data['data'] as &$v){
                $v['headimgurl'] = '<img style="width:30px;" src="'.$v['headimgurl'].'">';
                $v['acc_time'] = date('Y-m-d H:i:s',$v['acc_time']);
                $editAction   = url('edit',['id'=>$v['id']]);
                $removeAction = url('del',['id'=>$v['id']]);
                $v['buttons'] = sprintf('<a href="#" class="btn-edit" data-action="%s"><i class="fa fa-edit"></i></a>&nbsp;&nbsp;<a href="#" class="btn-remove" data-action="%s"><i class="fa fa-remove"></i></a>',$editAction,$removeAction);
            }
            exit(json_encode($data));
        }

        $tColumns = [
            ['data'=>'id','title'=>'自动编号','orderable'=>true],
            ['data'=>'wechat_id','title'=>'公众号','orderable'=>false],
            ['data'=>'nickname','title'=>'昵称','orderable'=>false],
            ['data'=>'openid','title'=>'openid','orderable'=>false],
            ['data'=>'sex','title'=>'性别','orderable'=>false],
            ['data'=>'headimgurl','title'=>'头像','orderable'=>false],
            ['data'=>'city','title'=>'城市','orderable'=>false],
            ['data'=>'subscribe','title'=>'关注状态'],
            ['data'=>'acc_time','title'=>'最后交互时间'],
            ['data'=>'buttons','title'=>'操作','orderable'=>false],
        ];

        $this->assign(['columns'=>json_encode($tColumns),'wechatListById'=>array_map(function($v){
            $v['link'] = url('index',['wechat_id'=>$v['id']]);
            return $v;
        },$wechatList)]);
        return view();
    }
    
    public function sync()
    {
        $res = \app\wechat\logic\Wuser::syncUser();
        return json($res);
    }
}